home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / rexec.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  24KB  |  639 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''Restricted execution facilities.
  5.  
  6. The class RExec exports methods r_exec(), r_eval(), r_execfile(), and
  7. r_import(), which correspond roughly to the built-in operations
  8. exec, eval(), execfile() and import, but executing the code in an
  9. environment that only exposes those built-in operations that are
  10. deemed safe.  To this end, a modest collection of \'fake\' modules is
  11. created which mimics the standard modules by the same names.  It is a
  12. policy decision which built-in modules and operations are made
  13. available; this module provides a reasonable default, but derived
  14. classes can change the policies e.g. by overriding or extending class
  15. variables like ok_builtin_modules or methods like make_sys().
  16.  
  17. XXX To do:
  18. - r_open should allow writing tmp dir
  19. - r_exec etc. with explicit globals/locals? (Use rexec("exec ... in ...")?)
  20.  
  21. '''
  22. from warnings import warnpy3k
  23. warnpy3k('the rexec module has been removed in Python 3.0', stacklevel = 2)
  24. del warnpy3k
  25. import sys
  26. import __builtin__
  27. import os
  28. import ihooks
  29. import imp
  30. __all__ = [
  31.     'RExec']
  32.  
  33. class FileBase:
  34.     ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline', 'readlines', 'seek', 'tell', 'write', 'writelines', 'xreadlines', '__iter__')
  35.  
  36.  
  37. class FileWrapper(FileBase):
  38.     
  39.     def __init__(self, f):
  40.         for m in self.ok_file_methods:
  41.             if not hasattr(self, m) and hasattr(f, m):
  42.                 setattr(self, m, getattr(f, m))
  43.                 continue
  44.         
  45.  
  46.     
  47.     def close(self):
  48.         self.flush()
  49.  
  50.  
  51. TEMPLATE = '\ndef %s(self, *args):\n        return getattr(self.mod, self.name).%s(*args)\n'
  52.  
  53. class FileDelegate(FileBase):
  54.     
  55.     def __init__(self, mod, name):
  56.         self.mod = mod
  57.         self.name = name
  58.  
  59.     for m in FileBase.ok_file_methods + ('close',):
  60.         exec TEMPLATE % (m, m)
  61.     
  62.  
  63.  
  64. class RHooks(ihooks.Hooks):
  65.     
  66.     def __init__(self, *args):
  67.         verbose = 0
  68.         rexec = None
  69.         if args and type(args[-1]) == type(0):
  70.             verbose = args[-1]
  71.             args = args[:-1]
  72.         
  73.         if args and hasattr(args[0], '__class__'):
  74.             rexec = args[0]
  75.             args = args[1:]
  76.         
  77.         if args:
  78.             raise TypeError, 'too many arguments'
  79.         args
  80.         ihooks.Hooks.__init__(self, verbose)
  81.         self.rexec = rexec
  82.  
  83.     
  84.     def set_rexec(self, rexec):
  85.         self.rexec = rexec
  86.  
  87.     
  88.     def get_suffixes(self):
  89.         return self.rexec.get_suffixes()
  90.  
  91.     
  92.     def is_builtin(self, name):
  93.         return self.rexec.is_builtin(name)
  94.  
  95.     
  96.     def init_builtin(self, name):
  97.         m = __import__(name)
  98.         return self.rexec.copy_except(m, ())
  99.  
  100.     
  101.     def init_frozen(self, name):
  102.         raise SystemError, "don't use this"
  103.  
  104.     
  105.     def load_source(self, *args):
  106.         raise SystemError, "don't use this"
  107.  
  108.     
  109.     def load_compiled(self, *args):
  110.         raise SystemError, "don't use this"
  111.  
  112.     
  113.     def load_package(self, *args):
  114.         raise SystemError, "don't use this"
  115.  
  116.     
  117.     def load_dynamic(self, name, filename, file):
  118.         return self.rexec.load_dynamic(name, filename, file)
  119.  
  120.     
  121.     def add_module(self, name):
  122.         return self.rexec.add_module(name)
  123.  
  124.     
  125.     def modules_dict(self):
  126.         return self.rexec.modules
  127.  
  128.     
  129.     def default_path(self):
  130.         return self.rexec.modules['sys'].path
  131.  
  132.  
  133. RModuleLoader = ihooks.FancyModuleLoader
  134. RModuleImporter = ihooks.ModuleImporter
  135.  
  136. class RExec(ihooks._Verbose):
  137.     '''Basic restricted execution framework.
  138.  
  139.     Code executed in this restricted environment will only have access to
  140.     modules and functions that are deemed safe; you can subclass RExec to
  141.     add or remove capabilities as desired.
  142.  
  143.     The RExec class can prevent code from performing unsafe operations like
  144.     reading or writing disk files, or using TCP/IP sockets.  However, it does
  145.     not protect against code using extremely large amounts of memory or
  146.     processor time.
  147.  
  148.     '''
  149.     ok_path = tuple(sys.path)
  150.     ok_builtin_modules = ('audioop', 'array', 'binascii', 'cmath', 'errno', 'imageop', 'marshal', 'math', 'md5', 'operator', 'parser', 'select', 'sha', '_sre', 'strop', 'struct', 'time', '_weakref')
  151.     ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink', 'stat', 'times', 'uname', 'getpid', 'getppid', 'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
  152.     ok_sys_names = ('byteorder', 'copyright', 'exit', 'getdefaultencoding', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'platform', 'ps1', 'ps2', 'version', 'version_info')
  153.     nok_builtin_names = ('open', 'file', 'reload', '__import__')
  154.     ok_file_types = (imp.C_EXTENSION, imp.PY_SOURCE)
  155.     
  156.     def __init__(self, hooks = None, verbose = 0):
  157.         """Returns an instance of the RExec class.
  158.  
  159.         The hooks parameter is an instance of the RHooks class or a subclass
  160.         of it.  If it is omitted or None, the default RHooks class is
  161.         instantiated.
  162.  
  163.         Whenever the RExec module searches for a module (even a built-in one)
  164.         or reads a module's code, it doesn't actually go out to the file
  165.         system itself.  Rather, it calls methods of an RHooks instance that
  166.         was passed to or created by its constructor.  (Actually, the RExec
  167.         object doesn't make these calls --- they are made by a module loader
  168.         object that's part of the RExec object.  This allows another level of
  169.         flexibility, which can be useful when changing the mechanics of
  170.         import within the restricted environment.)
  171.  
  172.         By providing an alternate RHooks object, we can control the file
  173.         system accesses made to import a module, without changing the
  174.         actual algorithm that controls the order in which those accesses are
  175.         made.  For instance, we could substitute an RHooks object that
  176.         passes all filesystem requests to a file server elsewhere, via some
  177.         RPC mechanism such as ILU.  Grail's applet loader uses this to support
  178.         importing applets from a URL for a directory.
  179.  
  180.         If the verbose parameter is true, additional debugging output may be
  181.         sent to standard output.
  182.  
  183.         """
  184.         raise RuntimeError, 'This code is not secure in Python 2.2 and later'
  185.         ihooks._Verbose.__init__(self, verbose)
  186.         if not hooks:
  187.             pass
  188.         self.hooks = RHooks(verbose)
  189.         self.hooks.set_rexec(self)
  190.         self.modules = { }
  191.         self.ok_dynamic_modules = self.ok_builtin_modules
  192.         list = []
  193.         for mname in self.ok_builtin_modules:
  194.             if mname in sys.builtin_module_names:
  195.                 list.append(mname)
  196.                 continue
  197.         
  198.         self.ok_builtin_modules = tuple(list)
  199.         self.set_trusted_path()
  200.         self.make_builtin()
  201.         self.make_initial_modules()
  202.         self.make_sys()
  203.         self.loader = RModuleLoader(self.hooks, verbose)
  204.         self.importer = RModuleImporter(self.loader, verbose)
  205.  
  206.     
  207.     def set_trusted_path(self):
  208.         self.trusted_path = filter(os.path.isabs, sys.path)
  209.  
  210.     
  211.     def load_dynamic(self, name, filename, file):
  212.         if name not in self.ok_dynamic_modules:
  213.             raise ImportError, 'untrusted dynamic module: %s' % name
  214.         name not in self.ok_dynamic_modules
  215.         if name in sys.modules:
  216.             src = sys.modules[name]
  217.         else:
  218.             src = imp.load_dynamic(name, filename, file)
  219.         dst = self.copy_except(src, [])
  220.         return dst
  221.  
  222.     
  223.     def make_initial_modules(self):
  224.         self.make_main()
  225.         self.make_osname()
  226.  
  227.     
  228.     def get_suffixes(self):
  229.         return _[1]
  230.  
  231.     
  232.     def is_builtin(self, mname):
  233.         return mname in self.ok_builtin_modules
  234.  
  235.     
  236.     def make_builtin(self):
  237.         m = self.copy_except(__builtin__, self.nok_builtin_names)
  238.         m.__import__ = self.r_import
  239.         m.reload = self.r_reload
  240.         m.open = m.file = self.r_open
  241.  
  242.     
  243.     def make_main(self):
  244.         m = self.add_module('__main__')
  245.  
  246.     
  247.     def make_osname(self):
  248.         osname = os.name
  249.         src = __import__(osname)
  250.         dst = self.copy_only(src, self.ok_posix_names)
  251.         dst.environ = e = { }
  252.         for key, value in os.environ.items():
  253.             e[key] = value
  254.         
  255.  
  256.     
  257.     def make_sys(self):
  258.         m = self.copy_only(sys, self.ok_sys_names)
  259.         m.modules = self.modules
  260.         m.argv = [
  261.             'RESTRICTED']
  262.         m.path = map(None, self.ok_path)
  263.         m.exc_info = self.r_exc_info
  264.         m = self.modules['sys']
  265.         l = self.modules.keys() + list(self.ok_builtin_modules)
  266.         l.sort()
  267.         m.builtin_module_names = tuple(l)
  268.  
  269.     
  270.     def copy_except(self, src, exceptions):
  271.         dst = self.copy_none(src)
  272.         for name in dir(src):
  273.             setattr(dst, name, getattr(src, name))
  274.         
  275.         for name in exceptions:
  276.             
  277.             try:
  278.                 delattr(dst, name)
  279.             continue
  280.             except AttributeError:
  281.                 continue
  282.             
  283.  
  284.         
  285.         return dst
  286.  
  287.     
  288.     def copy_only(self, src, names):
  289.         dst = self.copy_none(src)
  290.         for name in names:
  291.             
  292.             try:
  293.                 value = getattr(src, name)
  294.             except AttributeError:
  295.                 continue
  296.  
  297.             setattr(dst, name, value)
  298.         
  299.         return dst
  300.  
  301.     
  302.     def copy_none(self, src):
  303.         m = self.add_module(src.__name__)
  304.         m.__doc__ = src.__doc__
  305.         return m
  306.  
  307.     
  308.     def add_module(self, mname):
  309.         m = self.modules.get(mname)
  310.         if m is None:
  311.             self.modules[mname] = m = self.hooks.new_module(mname)
  312.         
  313.         m.__builtins__ = self.modules['__builtin__']
  314.         return m
  315.  
  316.     
  317.     def r_exec(self, code):
  318.         """Execute code within a restricted environment.
  319.  
  320.         The code parameter must either be a string containing one or more
  321.         lines of Python code, or a compiled code object, which will be
  322.         executed in the restricted environment's __main__ module.
  323.  
  324.         """
  325.         m = self.add_module('__main__')
  326.         exec code in m.__dict__
  327.  
  328.     
  329.     def r_eval(self, code):
  330.         """Evaluate code within a restricted environment.
  331.  
  332.         The code parameter must either be a string containing a Python
  333.         expression, or a compiled code object, which will be evaluated in
  334.         the restricted environment's __main__ module.  The value of the
  335.         expression or code object will be returned.
  336.  
  337.         """
  338.         m = self.add_module('__main__')
  339.         return eval(code, m.__dict__)
  340.  
  341.     
  342.     def r_execfile(self, file):
  343.         """Execute the Python code in the file in the restricted
  344.         environment's __main__ module.
  345.  
  346.         """
  347.         m = self.add_module('__main__')
  348.         execfile(file, m.__dict__)
  349.  
  350.     
  351.     def r_import(self, mname, globals = { }, locals = { }, fromlist = []):
  352.         '''Import a module, raising an ImportError exception if the module
  353.         is considered unsafe.
  354.  
  355.         This method is implicitly called by code executing in the
  356.         restricted environment.  Overriding this method in a subclass is
  357.         used to change the policies enforced by a restricted environment.
  358.  
  359.         '''
  360.         return self.importer.import_module(mname, globals, locals, fromlist)
  361.  
  362.     
  363.     def r_reload(self, m):
  364.         '''Reload the module object, re-parsing and re-initializing it.
  365.  
  366.         This method is implicitly called by code executing in the
  367.         restricted environment.  Overriding this method in a subclass is
  368.         used to change the policies enforced by a restricted environment.
  369.  
  370.         '''
  371.         return self.importer.reload(m)
  372.  
  373.     
  374.     def r_unload(self, m):
  375.         """Unload the module.
  376.  
  377.         Removes it from the restricted environment's sys.modules dictionary.
  378.  
  379.         This method is implicitly called by code executing in the
  380.         restricted environment.  Overriding this method in a subclass is
  381.         used to change the policies enforced by a restricted environment.
  382.  
  383.         """
  384.         return self.importer.unload(m)
  385.  
  386.     
  387.     def make_delegate_files(self):
  388.         s = self.modules['sys']
  389.         self.delegate_stdin = FileDelegate(s, 'stdin')
  390.         self.delegate_stdout = FileDelegate(s, 'stdout')
  391.         self.delegate_stderr = FileDelegate(s, 'stderr')
  392.         self.restricted_stdin = FileWrapper(sys.stdin)
  393.         self.restricted_stdout = FileWrapper(sys.stdout)
  394.         self.restricted_stderr = FileWrapper(sys.stderr)
  395.  
  396.     
  397.     def set_files(self):
  398.         if not hasattr(self, 'save_stdin'):
  399.             self.save_files()
  400.         
  401.         if not hasattr(self, 'delegate_stdin'):
  402.             self.make_delegate_files()
  403.         
  404.         s = self.modules['sys']
  405.         s.stdin = self.restricted_stdin
  406.         s.stdout = self.restricted_stdout
  407.         s.stderr = self.restricted_stderr
  408.         sys.stdin = self.delegate_stdin
  409.         sys.stdout = self.delegate_stdout
  410.         sys.stderr = self.delegate_stderr
  411.  
  412.     
  413.     def reset_files(self):
  414.         self.restore_files()
  415.         s = self.modules['sys']
  416.         self.restricted_stdin = s.stdin
  417.         self.restricted_stdout = s.stdout
  418.         self.restricted_stderr = s.stderr
  419.  
  420.     
  421.     def save_files(self):
  422.         self.save_stdin = sys.stdin
  423.         self.save_stdout = sys.stdout
  424.         self.save_stderr = sys.stderr
  425.  
  426.     
  427.     def restore_files(self):
  428.         sys.stdin = self.save_stdin
  429.         sys.stdout = self.save_stdout
  430.         sys.stderr = self.save_stderr
  431.  
  432.     
  433.     def s_apply(self, func, args = (), kw = { }):
  434.         self.save_files()
  435.         
  436.         try:
  437.             self.set_files()
  438.             r = func(*args, **kw)
  439.         finally:
  440.             self.restore_files()
  441.  
  442.         return r
  443.  
  444.     
  445.     def s_exec(self, *args):
  446.         """Execute code within a restricted environment.
  447.  
  448.         Similar to the r_exec() method, but the code will be granted access
  449.         to restricted versions of the standard I/O streams sys.stdin,
  450.         sys.stderr, and sys.stdout.
  451.  
  452.         The code parameter must either be a string containing one or more
  453.         lines of Python code, or a compiled code object, which will be
  454.         executed in the restricted environment's __main__ module.
  455.  
  456.         """
  457.         return self.s_apply(self.r_exec, args)
  458.  
  459.     
  460.     def s_eval(self, *args):
  461.         """Evaluate code within a restricted environment.
  462.  
  463.         Similar to the r_eval() method, but the code will be granted access
  464.         to restricted versions of the standard I/O streams sys.stdin,
  465.         sys.stderr, and sys.stdout.
  466.  
  467.         The code parameter must either be a string containing a Python
  468.         expression, or a compiled code object, which will be evaluated in
  469.         the restricted environment's __main__ module.  The value of the
  470.         expression or code object will be returned.
  471.  
  472.         """
  473.         return self.s_apply(self.r_eval, args)
  474.  
  475.     
  476.     def s_execfile(self, *args):
  477.         """Execute the Python code in the file in the restricted
  478.         environment's __main__ module.
  479.  
  480.         Similar to the r_execfile() method, but the code will be granted
  481.         access to restricted versions of the standard I/O streams sys.stdin,
  482.         sys.stderr, and sys.stdout.
  483.  
  484.         """
  485.         return self.s_apply(self.r_execfile, args)
  486.  
  487.     
  488.     def s_import(self, *args):
  489.         '''Import a module, raising an ImportError exception if the module
  490.         is considered unsafe.
  491.  
  492.         This method is implicitly called by code executing in the
  493.         restricted environment.  Overriding this method in a subclass is
  494.         used to change the policies enforced by a restricted environment.
  495.  
  496.         Similar to the r_import() method, but has access to restricted
  497.         versions of the standard I/O streams sys.stdin, sys.stderr, and
  498.         sys.stdout.
  499.  
  500.         '''
  501.         return self.s_apply(self.r_import, args)
  502.  
  503.     
  504.     def s_reload(self, *args):
  505.         '''Reload the module object, re-parsing and re-initializing it.
  506.  
  507.         This method is implicitly called by code executing in the
  508.         restricted environment.  Overriding this method in a subclass is
  509.         used to change the policies enforced by a restricted environment.
  510.  
  511.         Similar to the r_reload() method, but has access to restricted
  512.         versions of the standard I/O streams sys.stdin, sys.stderr, and
  513.         sys.stdout.
  514.  
  515.         '''
  516.         return self.s_apply(self.r_reload, args)
  517.  
  518.     
  519.     def s_unload(self, *args):
  520.         """Unload the module.
  521.  
  522.         Removes it from the restricted environment's sys.modules dictionary.
  523.  
  524.         This method is implicitly called by code executing in the
  525.         restricted environment.  Overriding this method in a subclass is
  526.         used to change the policies enforced by a restricted environment.
  527.  
  528.         Similar to the r_unload() method, but has access to restricted
  529.         versions of the standard I/O streams sys.stdin, sys.stderr, and
  530.         sys.stdout.
  531.  
  532.         """
  533.         return self.s_apply(self.r_unload, args)
  534.  
  535.     
  536.     def r_open(self, file, mode = 'r', buf = -1):
  537.         """Method called when open() is called in the restricted environment.
  538.  
  539.         The arguments are identical to those of the open() function, and a
  540.         file object (or a class instance compatible with file objects)
  541.         should be returned.  RExec's default behaviour is allow opening
  542.         any file for reading, but forbidding any attempt to write a file.
  543.  
  544.         This method is implicitly called by code executing in the
  545.         restricted environment.  Overriding this method in a subclass is
  546.         used to change the policies enforced by a restricted environment.
  547.  
  548.         """
  549.         mode = str(mode)
  550.         if mode not in ('r', 'rb'):
  551.             raise IOError, "can't open files for writing in restricted mode"
  552.         mode not in ('r', 'rb')
  553.         return open(file, mode, buf)
  554.  
  555.     
  556.     def r_exc_info(self):
  557.         (ty, va, tr) = sys.exc_info()
  558.         tr = None
  559.         return (ty, va, tr)
  560.  
  561.  
  562.  
  563. def test():
  564.     import getopt as getopt
  565.     import traceback as traceback
  566.     (opts, args) = getopt.getopt(sys.argv[1:], 'vt:')
  567.     verbose = 0
  568.     trusted = []
  569.     for o, a in opts:
  570.         if o == '-v':
  571.             verbose = verbose + 1
  572.         
  573.         if o == '-t':
  574.             trusted.append(a)
  575.             continue
  576.     
  577.     r = RExec(verbose = verbose)
  578.     if trusted:
  579.         r.ok_builtin_modules = r.ok_builtin_modules + tuple(trusted)
  580.     
  581.     if args:
  582.         r.modules['sys'].argv = args
  583.         r.modules['sys'].path.insert(0, os.path.dirname(args[0]))
  584.     else:
  585.         r.modules['sys'].path.insert(0, '')
  586.     fp = sys.stdin
  587.     if args and args[0] != '-':
  588.         
  589.         try:
  590.             fp = open(args[0])
  591.         except IOError:
  592.             msg = None
  593.             print "%s: can't open file %r" % (sys.argv[0], args[0])
  594.             return 1
  595.         
  596.  
  597.     None<EXCEPTION MATCH>IOError
  598.     if fp.isatty():
  599.         
  600.         try:
  601.             import readline
  602.         except ImportError:
  603.             pass
  604.  
  605.         import code
  606.         
  607.         class RestrictedConsole('RestrictedConsole', (code.InteractiveConsole,)):
  608.             
  609.             def runcode(self, co):
  610.                 self.locals['__builtins__'] = r.modules['__builtin__']
  611.                 r.s_apply(code.InteractiveConsole.runcode, (self, co))
  612.  
  613.  
  614.         
  615.         try:
  616.             RestrictedConsole(r.modules['__main__'].__dict__).interact()
  617.         except SystemExit:
  618.             n = None
  619.             return n
  620.         
  621.  
  622.     None<EXCEPTION MATCH>SystemExit
  623.     text = fp.read()
  624.     fp.close()
  625.     c = compile(text, fp.name, 'exec')
  626.     
  627.     try:
  628.         r.s_exec(c)
  629.     except SystemExit:
  630.         n = None
  631.         return n
  632.         traceback.print_exc()
  633.         return 1
  634.  
  635.  
  636. if __name__ == '__main__':
  637.     sys.exit(test())
  638.  
  639.